package com.hsl.test.servlet;

import com.alibaba.fastjson.JSONObject;
import com.hsl.test.pojo.Result;
import com.hsl.test.service.TransferService;
import com.hsl.test.utils.TestApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hsl
 * @Data 2021/12/14
 * @Desc
 */
@WebServlet(name = "transferServlet", urlPatterns = "/transfer")
public class TrannsferServlet extends HttpServlet {
    private TransferService transferService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置启动类扫描
        TestApplicationContext context = new TestApplicationContext("com.hsl.test");
        transferService = (TransferService) context.getBean("TransferService", context);
        request.setCharacterEncoding("UTF-8");
        //获取参数
        String transferFrom = request.getParameter("transferFrom");
        String transferTo = request.getParameter("transferTo");
        int money = Integer.parseInt(request.getParameter("money"));
        Result result = new Result();
        try {
            transferService.transfer(transferFrom,transferTo,money);
            result.setStatus("200");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus("500");
            result.setMessage(e.getMessage());
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(JSONObject.toJSONString(result));
    }
}
